package com.misty.proxy_pattern.client_dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxy implements InvocationHandler {
    private Object target;

    public DynamicProxy(Object object) {
        this.target = object;
    }

    //生成目标对象的代理对象
    public Object bind() {
        Class cls = target.getClass();
        return Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //这里可以根据目标类型来编写业务逻辑
        Object arg = args[0];
        before();
        Object obj = method.invoke(target, args);
        after();
        return obj;
    }

    private void before() {
        System.out.println(" 动态代理 before ");
    }

    private void after() {
        System.out.println(" 动态代理 after ");
    }
}
